import { useDebounceFn } from '@vueuse/core';
import { computed, type ComputedRef, nextTick, type Ref, unref, watch } from 'vue';
import type { PaginationProps } from 'element-plus';
import type { PaginationPropsType } from '../types/pagination';
import { isObject, isUndefined } from 'lodash-es';
import type { BasicTableProps } from '../types/table';
import type { ComponentRef } from '#/types/global';

export function useVxeTableScroll(
  propsRef: ComputedRef<BasicTableProps>,
  setProps: (props: Partial<BasicTableProps>) => void,
  formRef: Ref<ComponentRef>,
  getPaginationInfo: ComputedRef<boolean | PaginationProps | PaginationPropsType>,
  wrapRef: Ref<HTMLElement | null>,
  bodyRef: Ref<HTMLElement | null>,
) {
  const debounceRedoHeight = useDebounceFn(redoHeight, 100);

  const getCanResize = computed(() => {
    const { canResize, resizeHeightOffset } = unref(propsRef);
    return canResize || resizeHeightOffset != 0;
  });

  watch(
    () => unref(getCanResize),
    (val) => {
      if (val) {
        debounceRedoHeight();
      }
    },
    {
      immediate: true,
      deep: true,
      flush: 'post',
    },
  );

  function redoHeight() {
    nextTick(() => {
      calcTableHeight();
    });
  }
  async function calcTableHeight() {
    const { resizeHeightOffset = 0, maxHeight } = unref(propsRef);
    //父元素高度
    const wrapParentHeight = (unref(wrapRef)?.parentNode as HTMLElement).offsetHeight ?? 0;
    const bodyHeight = unref(bodyRef)?.offsetHeight ?? 0;
    const formHeight = unref(formRef) ? unref(formRef)?.$el.offsetHeight : 0;
    let paginationHeight = 0;
    if (isObject(getPaginationInfo)) {
      const aa = document.getElementById('tablePagination');
      paginationHeight = aa?.offsetHeight || 0;
    }
    let height =
      wrapParentHeight - formHeight! - paginationHeight - resizeHeightOffset - bodyHeight;
    if (!isUndefined(maxHeight)) {
      height = maxHeight > height ? height : maxHeight;
    }
    console.log('height', height, wrapParentHeight, unref(wrapRef)?.parentNode as HTMLElement);
    if (wrapParentHeight) {
      setProps({
        height: `${height}px`,
      });
    }
  }
  return { redoHeight };
}
